import { authenticateToken } from "../../../lib/auth.js";
import { getConnection } from "../../../lib/db.js";
import { validateLookupType } from "../../../lib/validation.js";

const handler = async function handler(req, res) {
  try {
    const user = req.user;
    const { id } = req.query;
    const connection = await getConnection();

    // 验证字典类型是否存在且属于当前租户
    const [typeResult] = await connection.execute(
      "SELECT * FROM lookup_types WHERE id = ? AND tenant_id = ?",
      [id, user.tenant_id]
    );

    if (typeResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: "字典类型不存在",
      });
    }

    const lookupType = typeResult[0];

    if (req.method === "GET") {
      // 获取字典类型详情
      res.status(200).json({
        success: true,
        data: lookupType,
      });
    } else if (req.method === "PUT") {
      // 更新字典类型
      if (user.role !== "administrator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，只有管理员才能修改字典类型",
        });
      }

      // 系统预置类型不允许修改代码和名称
      if (
        lookupType.is_system &&
        (req.body.code !== lookupType.code || req.body.name !== lookupType.name)
      ) {
        return res.status(400).json({
          success: false,
          message: "系统预置字典类型不允许修改代码和名称",
        });
      }

      const validation = validateLookupType(req.body);
      if (!validation.success) {
        return res.status(400).json({
          success: false,
          message: validation.message,
          errors: validation.errors,
        });
      }

      const { code, name, description, sort_order, status } = req.body;

      // 如果修改了代码，检查是否重复
      if (code !== lookupType.code) {
        const [existingType] = await connection.execute(
          "SELECT id FROM lookup_types WHERE tenant_id = ? AND code = ? AND id != ?",
          [user.tenant_id, code, id]
        );

        if (existingType.length > 0) {
          return res.status(400).json({
            success: false,
            message: "字典类型代码已存在",
          });
        }
      }

      const updateQuery = `
        UPDATE lookup_types 
        SET code = ?, name = ?, description = ?, sort_order = ?, status = ?, updated_at = NOW()
        WHERE id = ? AND tenant_id = ?
      `;

      await connection.execute(updateQuery, [
        code,
        name,
        description,
        sort_order || 0,
        status !== undefined ? status : 1,
        id,
        user.tenant_id,
      ]);

      res.status(200).json({
        success: true,
        message: "字典类型更新成功",
      });
    } else if (req.method === "DELETE") {
      // 删除字典类型
      if (user.role !== "administrator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，只有管理员才能删除字典类型",
        });
      }

      // 系统预置类型不允许删除
      if (lookupType.is_system) {
        return res.status(400).json({
          success: false,
          message: "系统预置字典类型不允许删除",
        });
      }

      // 检查是否有关联的字典项
      const [itemCount] = await connection.execute(
        "SELECT COUNT(*) as count FROM lookup_items WHERE tenant_id = ? AND type_id = ?",
        [user.tenant_id, id]
      );

      if (itemCount[0].count > 0) {
        return res.status(400).json({
          success: false,
          message: `无法删除，该字典类型下还有 ${itemCount[0].count} 个字典项`,
        });
      }

      await connection.execute(
        "DELETE FROM lookup_types WHERE id = ? AND tenant_id = ?",
        [id, user.tenant_id]
      );

      res.status(200).json({
        success: true,
        message: "字典类型删除成功",
      });
    } else {
      res.status(405).json({
        success: false,
        message: "不支持的请求方法",
      });
    }
  } catch (error) {
    console.error("Lookup type API error:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

export default authenticateToken(handler);
